package com.yune.adapter;

import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.yune.R;
import com.yune.bean.HistoryBean;
import com.yune.utils.Network;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

public class HistoryListAdapter extends ArrayAdapter<HistoryBean> {
    private static final int layoutId = R.layout.item_song;
    private final Activity context;

    public HistoryListAdapter(Activity context, List<HistoryBean> objects){
        super(context,layoutId,objects);
        this.context=context;
    }
    @Override
    public View getView(int position, View convertView, ViewGroup parent){
        HistoryBean historyBean = getItem(position);
        View view;
        ViewHolder viewHolder;
        if (convertView==null){
            view=LayoutInflater.from(getContext()).inflate(layoutId,parent,false);
            viewHolder= new ViewHolder();
            viewHolder.title=view.findViewById(R.id.find_item_title);
            viewHolder.author=view.findViewById(R.id.find_item_author);
            viewHolder.img=view.findViewById(R.id.find_item_img);
            view.setTag(viewHolder);
        } else{
            view=convertView;
            viewHolder=(ViewHolder) view.getTag();
        }
        Network.get("https://api2.bmob.cn/1/classes/song/" + historyBean.songOid, res1 -> {
            JSONObject result1 = new JSONObject(res1);
            viewHolder.title.setText(result1.getString("songName"));
            viewHolder.author.setText(result1.getString("singer"));
            DisplayImageOptions options = new DisplayImageOptions.Builder()
                    .showImageOnLoading(R.drawable.loading)// 设置图片下载期间显示的图片
                    .showImageForEmptyUri(R.drawable.loaderror)// 设置图片Uri为空或是错误的时候显示的图片
                    .showImageOnFail(R.drawable.loaderror)// 设置图片加载或解码过程中发生错误显示的图片
                    .cacheInMemory(true)// 设置下载的图片是否缓存在内存中
                    .cacheOnDisk(false)// 设置下载的图片是否缓存在SD卡中
                    .displayer(new RoundedBitmapDisplayer(20))// 设置成圆角图片
                    .build();
            context.runOnUiThread(() -> {
                try {
                    ImageLoader.getInstance().displayImage(result1.getString("picture"),viewHolder.img,options);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            });
        });
        return view;
    }
    static class ViewHolder{
        ImageView img;
        TextView title,author;
    }
}